package de.guice.aktenschrank.crud;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import com.google.inject.Inject;

import de.guice.aktenschrank.configuration.Annotation.Trace;
import de.guice.aktenschrank.entities.AkteData;

public class AkteDAOJDBCImpl implements AkteDAO {

	@Inject
	ConnectionManager cm;

	@Override
	@Trace("Akte Speichern")
	public AkteData create(AkteData akte) throws Throwable {

		StringBuilder sb = new StringBuilder();
		sb.append("INSERT INTO akte (akte_name,akte_inhalt) VALUES (");
		sb.append("'");
		sb.append(akte.getAktenName());
		sb.append("',");
		sb.append("'");
		sb.append(akte.getInhalt());
		sb.append("'");
		sb.append(")");

		try {

			Connection c = cm.getConnection();
			Statement s = c.createStatement();

			s.executeUpdate(sb.toString());
		} catch (Throwable e) {
			throw new Throwable("Error Persisting Data: " + e.getMessage());
		}
		return akte;
	}

	@Override
	public void delete(AkteData akte) throws Throwable {

		StringBuilder sb = new StringBuilder();
		sb.append("DELETE FROM akte WHERE id = ");
		sb.append("'");
		sb.append(akte.getId());
		sb.append("'");
		sb.append(")");

		try {

			Connection c = cm.getConnection();
			Statement s = c.createStatement();

			s.executeUpdate(sb.toString());
		} catch (Throwable e) {
			throw new Throwable("Error Persisting Data: " + e.getMessage());
		}

	}

	@Override
	public AkteData read(AkteData akte) throws Throwable {
		ResultSet resultSet = null;

		StringBuilder sb = new StringBuilder();
		sb.append("SELECT * FROM akte WHERE id = ");
		sb.append("'");
		sb.append(akte.getId());
		sb.append("'");
		sb.append(")");

		try {

			Connection c = cm.getConnection();
			Statement s = c.createStatement();

			resultSet = s.executeQuery(sb.toString());
			akte.setAktenName(resultSet.getString(1));
			akte.setInhalt(resultSet.getString(2));

		} catch (Throwable e) {
			throw new Throwable("Error Persisting Data: " + e.getMessage());
		}

		return akte;
	}

	@Override
	public AkteData update(AkteData akte) throws Throwable {
		StringBuilder sb = new StringBuilder();
		sb.append("UPDATE akte SET ");
		sb.append("akte_name = '");
		sb.append(akte.getAktenName());
		sb.append("',");
		sb.append("akte_inhalt = '");
		sb.append(akte.getInhalt());
		sb.append("'");
		sb.append("WHERE id = ");
		sb.append(akte.getId());
		

		try {

			Connection c = cm.getConnection();
			Statement s = c.createStatement();

			s.executeUpdate(sb.toString());
		} catch (Throwable e) {
			throw new Throwable("Error Persisting Data: " + e.getMessage());
		}
		return akte;
	}
}
